package com.jiantong.admin.controller.report;

import com.google.common.collect.Maps;
import com.jiantong.admin.dto.BreedDocumentReportFormDto;
import com.jiantong.admin.dto.CityAreaDto;
import com.jiantong.admin.model.PagingMz;
import com.jiantong.admin.util.ExportOrImportUtils;
import com.jiantong.user.model.*;
import com.jiantong.user.service.*;
import com.jiantong.version.model.DrugOrVaccine;
import com.jiantong.version.service.DrugOrVaccineReadService;
import com.jiantong.web.core.enums.ExceptionCode;
import com.jiantong.work.enums.DocumentsDeleteFlag;
import com.jiantong.work.service.*;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by mz on 12/10/17.
 */
@Slf4j
@Controller
public class BreedDocumentReportFormController {


    @RpcConsumer
    private UserReadService userReadService;
    @RpcConsumer
    private UserProfileReadService userProfileReadService;
    @RpcConsumer
    private GovernmentUserDutyReadService governmentUserDutyReadService;
    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;

    @RpcConsumer
    private DeclareStationReadService declareStationReadService;

    @RpcConsumer
    private DepartmentExtendReadService departmentExtendReadService;

    @RpcConsumer
    private ButcherFactoryReadService butcherFactoryReadService;


    //生产中心
    @RpcConsumer
    private ProductionReportReadService productionReportReadService;

    @RpcConsumer
    private FeedReportReadService feedReportReadService;

    @RpcConsumer
    private VeterinaryDrugsReportReadService veterinaryDrugsReportReadService;

    //采购中心
    @RpcConsumer
    private MaterialPurchaseRecordReadService materialPurchaseRecordReadService;

    @RpcConsumer
    private DrugPurchaseRecordReadService drugPurchaseRecordReadService;

    @RpcConsumer
    private VaccinePurchaseRecordReadService vaccinePurchaseRecordReadService;

    @RpcConsumer
    private SeedPurchaseRecordReadService seedPurchaseRecordReadService;

    @RpcConsumer
    private OtherPurchaseRecordReadService otherPurchaseRecordReadService;

    //免疫中心
    @RpcConsumer
    private ImmunizationRecordReadService immunizationRecordReadService;

    @RpcConsumer
    private ImmunizationSubRecordReadService immunizationSubRecordReadService;

    @RpcConsumer
    private DisinfectReportReadService disinfectReportReadService;

    @RpcConsumer
    private DiagnosisReportReadService diagnosisReportReadService;

    @RpcConsumer
    private ImmunizationDetectionReadService immunizationDetectionReadService;

    @RpcConsumer
    private QuarantineCenterHarmlessReadService quarantineCenterHarmlessReadService;

    //治污中心
    @RpcConsumer
    private PollutionControlReadService pollutionControlReadService;

    @RpcConsumer
    private DrugOrVaccineReadService drugOrVaccineReadService;


    @GetMapping("/djt/report/breedDocumentReportForm")
    public String aa(Model model, HttpServletRequest request, HttpServletResponse response) {

        Map loginUserMap = getarea(response, request);

        model.addAttribute("breedFactoryList", loginUserMap.get("breedFactorys"));
        model.addAttribute("username", loginUserMap.get("username"));
        model.addAttribute("cityAreaDtoList", loginUserMap.get("cityAreaDtoList"));
        model.addAttribute("declareStations", loginUserMap.get("declareStations"));
        return "/djt/report/breedDocumentReportForm";
    }


    @GetMapping("/djt/report/breedDocumentReportFormB")
    @ResponseBody
    public PagingMz<BreedDocumentReportFormDto> breedDocumentReportFormDtoPagingMz(@RequestParam(required = false) Integer page,
                                                                                   @RequestParam(required = false) Integer rows,
                                                                                   @RequestParam(required = false) Date start,
                                                                                   @RequestParam(required = false) Date end,
                                                                                   @RequestParam(required = false) String area,
                                                                                   @RequestParam(required = false) Integer breedType,
                                                                                   HttpServletRequest httpServletRequest,
                                                                                   HttpServletResponse httpServletResponse) {

        Map<String, Object> loginUserMap = getarea(httpServletResponse, httpServletRequest);

        List<BreedFactory> breedFactories = (List<BreedFactory>) loginUserMap.get("breedFactorys");

        List<Long> ids = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactories) {
            ids.add(breedFactory.getId());
        }

        page = page == null ? 1 : page;
        rows = rows == null ? 20 : rows;
        Map<String, Object> criteria = Maps.newHashMap();
        criteria.put("ids", ids);//todo
        if (breedType != null && breedType != -1) {
            criteria.put("breedType", breedType);
        }

        if(area != null && !area.isEmpty() && !area.equals("全部")){
            criteria.put("area",area);
        }

        //养殖场的数据获取
        Response<Paging<BreedFactory>> response = breedFactoryReadService.pagingForDocument(page, rows, criteria);

        if (!response.isSuccess()) {
            log.error("failed to paging factory , case = {}", response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(), response.getError());
        }

        List<BreedFactory> breedFactoryList = response.getResult().getData();

        List<BreedDocumentReportFormDto> breedDocumentReportFormDtos = new ArrayList<>();

        for (BreedFactory breedFactory : breedFactoryList) {
            BreedDocumentReportFormDto breedDocumentReportFormDto = new BreedDocumentReportFormDto();

            breedDocumentReportFormDto.setBreedFactoryId(breedFactory.getId());
            breedDocumentReportFormDto.setBreedFactoryName(breedFactory.getName());
            breedDocumentReportFormDto.setBreedType(breedFactory.getBreedType());

            Map<String, Object> map = Maps.newHashMap();
            if (start != null) map.put("start", start);
            if (start != null) map.put("end", end);
            map.put("breedFactoryId", breedFactory.getId());

            map.put("status", 1);
            map.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            //生产中心数据获取
            //todo 1、生产记录
            Response<Map<String, Object>> productionMapRes = productionReportReadService.findSumForWeb(map);
            if (!productionMapRes.isSuccess()) {
                log.error("failed to sum production ,case = {}", productionMapRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(), productionMapRes.getError());
            }
            Map<String, Object> productionMap = productionMapRes.getResult();
            /*
            SUM(change_quantity) AS sumChangeQuantity ,
            SUM(birth_quantity) AS sumBirthQuantity,
            SUM(in_quantity) AS sumInQuantity,
            SUM(out_quantity) AS sumOutQuantity,
            SUM(death_quantity) AS sumDeathQuantity
             */
            if(productionMap != null && !productionMap.isEmpty()){
                breedDocumentReportFormDto.setSumProduction(((BigDecimal) productionMap.getOrDefault("sumChangeQuantity",0)).intValue());
            }else {
                breedDocumentReportFormDto.setSumProduction(0);
            }

            breedDocumentReportFormDto.setProductionInfo(productionMap);
            //todo 2、饲料记录

            Response<Integer> countFeedRes = feedReportReadService.countForWeb(map);
            if(!countFeedRes.isSuccess()){
                log.error("failed to count feed report times , case = {}",countFeedRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countFeedRes.getError());
            }
            breedDocumentReportFormDto.setCountFeedReport(countFeedRes.getResult());
            /*
            SUM(used_quantity) AS sumUsedQuantity,
            feed_type AS feedType
             */
            Response<List<Map<String , Object>>> feedReportMapRes = feedReportReadService.findSumForWeb(map);
            if(!feedReportMapRes.isSuccess()){
                log.error("failed to find sum info , case = {}",feedReportMapRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),feedReportMapRes.getError());
            }
            breedDocumentReportFormDto.setFeedReportInfo(feedReportMapRes.getResult());

            //采购中心数据获取
            //todo 1、原料购置
            Response<Double> totalOfMaterialRes = materialPurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfMaterialRes.isSuccess()){
                log.error("failed to sum total price material , case = {}",totalOfMaterialRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfMaterialRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfMaterialPurchase(totalOfMaterialRes.getResult() == null ? 0.00d : totalOfMaterialRes.getResult());

            /*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> materialInfoRes = materialPurchaseRecordReadService.findMaterialForWeb(map);
            if(!materialInfoRes.isSuccess()){
                log.error("failed to find material info , case = {}",materialInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),materialInfoRes.getError());
            }
            breedDocumentReportFormDto.setMaterialPurchaseReportInfo(materialInfoRes.getResult());

            //todo 2、药物购置
            Response<Double> totalOfDrugRes = drugPurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfDrugRes.isSuccess()){
                log.error("failed to sum total price drug , case = {}",totalOfDrugRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfDrugRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfDrugPurchase(totalOfDrugRes.getResult() == null ? 0.00d : totalOfDrugRes.getResult());
/*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> drugPurchaseInfoRes = drugPurchaseRecordReadService.findDrugPurchaseForWeb(map);
            if(!drugPurchaseInfoRes.isSuccess()){
                log.error("failed to find drug purchase info , case = {}",drugPurchaseInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),drugPurchaseInfoRes.getError());
            }
            breedDocumentReportFormDto.setDrugPurchaseReportInfo(drugPurchaseInfoRes.getResult());

            //todo 3、疫苗购置
            Response<Double> totalOfVaccineRes = vaccinePurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfVaccineRes.isSuccess()){
                log.error("failed to total price for web , case = {}",totalOfVaccineRes);
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfVaccineRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfVaccinePurchase(totalOfVaccineRes.getResult() == null ? 0.00d : totalOfVaccineRes.getResult());
/*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> vaccinePurchaseInfoRes = vaccinePurchaseRecordReadService.findVaccinePurchaseInfoWeb(map);
            if(!vaccinePurchaseInfoRes.isSuccess()){
                log.error("failed to find vaccine purchase , case = {}",vaccinePurchaseInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),vaccinePurchaseInfoRes.getError());
            }
            breedDocumentReportFormDto.setVaccinePurchaseReportInfo(vaccinePurchaseInfoRes.getResult());

            //todo 4、引种记录
            Response<Double> totalOfSeedRes = seedPurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfSeedRes.isSuccess()){
                log.error("failed to sum total price , case = {}",totalOfSeedRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfSeedRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfSeedPurchase(totalOfSeedRes.getResult() == null ? 0.00d : totalOfSeedRes.getResult());
            /*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> seedPurchaseInfoRes = seedPurchaseRecordReadService.findSeedPurchaseInfoWeb(map);
            if(!seedPurchaseInfoRes.isSuccess()){
                log.error("failed to find seed purchase info , case ={}",seedPurchaseInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),seedPurchaseInfoRes.getError());
            }
            breedDocumentReportFormDto.setSeedPurchaseReportInfo(seedPurchaseInfoRes.getResult());

            //todo 5、其他购置
            Response<Double> totalOfOtherRes = otherPurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfOtherRes.isSuccess()){
                log.error("failed to sum price , case = {}",totalOfOtherRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfOtherRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfOtherPurchase(totalOfOtherRes.getResult() == null ? 0.00d : totalOfOtherRes.getResult());

            /*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> otherPurchaseInfoRes = otherPurchaseRecordReadService.findOtherPurchaseInfoWeb(map);
            if(!otherPurchaseInfoRes.isSuccess()){
                log.error("failed to find other purchase info web , case = {}",otherPurchaseInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),otherPurchaseInfoRes.getError());
            }
            breedDocumentReportFormDto.setOtherPurchaseReportInfo(otherPurchaseInfoRes.getResult());

            //防疫中心数据获取
            //todo 1、免疫记录

            Response<List<Long>> immunizationIdsRes = immunizationRecordReadService.findIdsForWeb(map);
            if(!immunizationIdsRes.isSuccess()){
                log.error("failed to get immunization ids ,case = {}",immunizationIdsRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),immunizationIdsRes.getError());
            }
            if(immunizationIdsRes.getResult() != null && !immunizationIdsRes.getResult().isEmpty()){
                map.put("vaccineIds",immunizationIdsRes.getResult());
                Response<Integer> countImmunizationRes = immunizationSubRecordReadService.countImmunizationForWeb(map);
                if(!countImmunizationRes.isSuccess()){
                    log.error("failed to count immunization times , case = {}",countImmunizationRes.getError());
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countImmunizationRes.getError());
                }
                breedDocumentReportFormDto.setCountImmunizationRecord(countImmunizationRes.getResult() == null ? 0:countImmunizationRes.getResult());

                /*
                          SUM (quantity) AS quantity,
                          SUM (drug_quantity) AS drugQuantity,
                          vaccine_code AS vaccineCode
                 */
                Response<List<Map<String , Object>>> immunizationInfoRes = immunizationSubRecordReadService.findImmunizationInfoForWeb(map);
                if(!immunizationInfoRes.isSuccess()){
                    log.error("failed to find immunization info , case = {}",immunizationInfoRes.getError());
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),immunizationInfoRes.getError());
                }
                breedDocumentReportFormDto.setImmunizationRecordInfo(immunizationInfoRes.getResult());
            }else {
                breedDocumentReportFormDto.setCountImmunizationRecord(0);
                breedDocumentReportFormDto.setImmunizationRecordInfo(new ArrayList<>());
            }

            //todo 2、消毒记录
            Response<Integer> countDisinfectRes = disinfectReportReadService.countDisinfectForWeb(map);
            if(!countDisinfectRes.isSuccess()){
                log.error("failed to count times , case = {}",countDisinfectRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countDisinfectRes.getError());
            }
            breedDocumentReportFormDto.setCountDisinfect(countDisinfectRes.getResult());

            /*
             SUM (drug_used_quantity) AS drugUsedQuantity,
             disinfectMethod AS disinfectMethod,
             */
            Response<List<Map<String , Object>>> disinfectReportInfoRes = disinfectReportReadService.findDisinfectInfoForWeb(map);
            if(!disinfectReportInfoRes.isSuccess()){
                log.error("failed to find disinfect info , case = {}",disinfectReportInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),disinfectReportInfoRes.getError());
            }
            breedDocumentReportFormDto.setDisinfectReportInfo(disinfectReportInfoRes.getResult());

            //todo 3、诊疗记录
            Response<Integer> countDiagnosisRes = diagnosisReportReadService.countDiagnosisTimesForWeb(map);
            if(!countDiagnosisRes.isSuccess()){
                log.error("failed to count times , case = {}",countDiagnosisRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countDiagnosisRes.getError());
            }
            breedDocumentReportFormDto.setCountDiagnosis(countDiagnosisRes.getResult());

            /*
             SUM (cases) AS cases,
             illness_reason AS illnessReason
             */
            Response<List<Map<String , Object>>> diagnosisInfoRes = diagnosisReportReadService.findDiagnosisInfoForWeb(map);
            if(!diagnosisInfoRes.isSuccess()){
                log.error("failed to find diagnosis info , case = {}",diagnosisInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),diagnosisInfoRes.getError());
            }
            breedDocumentReportFormDto.setDiagnosisReportInfo(diagnosisInfoRes.getResult());

            //todo 4、检验检测
            Response<Integer> countImmunizationDetectionRes = immunizationDetectionReadService.countImmunizationDetectionForWeb(map);
            if(!countImmunizationDetectionRes.isSuccess()){
                log.error("failed to count times , case = {}",countImmunizationDetectionRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countImmunizationDetectionRes.getError());
            }
            breedDocumentReportFormDto.setCountImmunizationDetection(countImmunizationDetectionRes.getResult());

            /*
             SUM (quantity) AS quantity,
             sample_type AS sampleType
             */
            Response<List<Map<String , Object>>> immunizationDetectionInfoRes = immunizationDetectionReadService.findImmunizationDetectionInfoForWeb(map);
            if(!immunizationDetectionInfoRes.isSuccess()){
                log.error("failed to find immunization detection info , case = {}",immunizationDetectionInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),immunizationDetectionInfoRes.getError());
            }
            breedDocumentReportFormDto.setImmunizationDetectionReportInfo(immunizationDetectionInfoRes.getResult());

            //todo 5、无害化处理
            Response<Integer> sumQuantityHarmlessRes = quarantineCenterHarmlessReadService.sumQuantityHarmlessForWeb(map);
            if(!sumQuantityHarmlessRes.isSuccess()){
                log.error("failed to sum quantity harmless , case = {}",sumQuantityHarmlessRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),sumQuantityHarmlessRes.getError());
            }
            breedDocumentReportFormDto.setSumQuarantineHarmless(sumQuantityHarmlessRes.getResult());

            /*
             SUM (quantity) AS quantity,
             treatment AS treatment
             */
            Response<List<Map<String , Object>>> quarantineHarmlessInfoRes = quarantineCenterHarmlessReadService.findQuarantineHarmlessInfoForWeb(map);
            if(!quarantineHarmlessInfoRes.isSuccess()){
                log.error("failed to find quarantine harmless , case = {}",quarantineHarmlessInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),quarantineHarmlessInfoRes.getError());
            }
            breedDocumentReportFormDto.setQuarantineHarmlessInfo(quarantineHarmlessInfoRes.getResult());


            //治污中心数据获取
            Response<Map<String , Object>> sumPollutionRes = pollutionControlReadService.sumPollutionForWeb(map);
            if(!sumPollutionRes.isSuccess()){
                log.error("failed to sum pollution , case = {}",sumPollutionRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),sumPollutionRes.getError());
            }
            Map<String , Object> sumPollutionMap = sumPollutionRes.getResult();
            if(sumPollutionMap != null && !sumPollutionMap.isEmpty()){
                breedDocumentReportFormDto.setSumOfDry((Double) sumPollutionRes.getResult().getOrDefault("dryUsedQuantity",0.00d));
                breedDocumentReportFormDto.setSumOfLiquid((Double) sumPollutionRes.getResult().getOrDefault("liquidUsedQuantity",0.00d));
            }else {
                breedDocumentReportFormDto.setSumOfDry(0.00d);
                breedDocumentReportFormDto.setSumOfLiquid(0.00d);
            }



            breedDocumentReportFormDtos.add(breedDocumentReportFormDto);
        }
        Long total = response.getResult().getTotal();
        Long pageTotal = (total - 1) / rows + 1;
        return new PagingMz<>(pageTotal, total, page, breedDocumentReportFormDtos);
    }

    @GetMapping("/djt/report/productionReportInfo")
    public String getProductionInfo(){
        return "/djt/report/productionReportInfo";
    }

    @GetMapping("/get/find/by/code/vaccine")
    @ResponseBody
    public DrugOrVaccine findByCode(@RequestParam(required = true)Integer code,
                                    @RequestParam(required = true)Integer type){

        Map<String , Object> map = Maps.newHashMap();

        map.put("code",code);

        map.put("type",code);

        map.put("deleteFlag",DocumentsDeleteFlag.NORMAL.value());

        Response<DrugOrVaccine> response = drugOrVaccineReadService.findByCode(map);
        if(!response.isSuccess()){
            log.error("failed to find by code ,  case = {}",response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }

        return response.getResult();
    }

    @GetMapping("/getExcel/breed/document/{start}/{end}/{area}/{breedType}")
    public void download(@PathVariable(value = "start")Date start,
                         @PathVariable(value = "end")Date end,
                         @PathVariable(value = "area")String area,
                         @PathVariable(value = "breedType")Integer breedType,
                         HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse) throws IOException {
        Map<String, Object> loginUserMap = getarea(httpServletResponse, httpServletRequest);

        List<BreedFactory> breedFactories = (List<BreedFactory>) loginUserMap.get("breedFactorys");

        List<Long> ids = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactories) {
            ids.add(breedFactory.getId());
        }
        Map<String, Object> criteria = Maps.newHashMap();
        criteria.put("ids", ids);//todo
        if (breedType != null && breedType != -1) {
            criteria.put("breedType", breedType);
        }

        if(area != null && !area.isEmpty() && !area.equals("全部")){
            criteria.put("area",area);
        }

        Response<List<BreedFactory>> response = breedFactoryReadService.findListForWebReport(criteria);
        if(!response.isSuccess()){
            log.error("failed to find list, case = {}",response.getError());
            throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),response.getError());
        }
        List<BreedFactory> breedFactoryList = response.getResult();

        List<BreedDocumentReportFormDto> breedDocumentReportFormDtos = new ArrayList<>();

        for (BreedFactory breedFactory : breedFactoryList) {
            BreedDocumentReportFormDto breedDocumentReportFormDto = new BreedDocumentReportFormDto();

            breedDocumentReportFormDto.setBreedFactoryId(breedFactory.getId());
            breedDocumentReportFormDto.setBreedFactoryName(breedFactory.getName());
            breedDocumentReportFormDto.setBreedType(breedFactory.getBreedType());

            Map<String, Object> map = Maps.newHashMap();
            if (start != null) map.put("start", start);
            if (start != null) map.put("end", end);
            map.put("breedFactoryId", breedFactory.getId());

            map.put("status", 1);
            map.put("deleteFlag", DocumentsDeleteFlag.NORMAL.value());
            //生产中心数据获取
            //todo 1、生产记录
            Response<Map<String, Object>> productionMapRes = productionReportReadService.findSumForWeb(map);
            if (!productionMapRes.isSuccess()) {
                log.error("failed to sum production ,case = {}", productionMapRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(), productionMapRes.getError());
            }
            Map<String, Object> productionMap = productionMapRes.getResult();
            /*
            SUM(change_quantity) AS sumChangeQuantity ,
            SUM(birth_quantity) AS sumBirthQuantity,
            SUM(in_quantity) AS sumInQuantity,
            SUM(out_quantity) AS sumOutQuantity,
            SUM(death_quantity) AS sumDeathQuantity
             */
            if(productionMap != null && !productionMap.isEmpty()){
                breedDocumentReportFormDto.setSumProduction(((BigDecimal) productionMap.getOrDefault("sumChangeQuantity",0)).intValue());
            }else {
                breedDocumentReportFormDto.setSumProduction(0);
            }

            breedDocumentReportFormDto.setProductionInfo(productionMap);
            //todo 2、饲料记录

            Response<Integer> countFeedRes = feedReportReadService.countForWeb(map);
            if(!countFeedRes.isSuccess()){
                log.error("failed to count feed report times , case = {}",countFeedRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countFeedRes.getError());
            }
            breedDocumentReportFormDto.setCountFeedReport(countFeedRes.getResult());
            /*
            SUM(used_quantity) AS sumUsedQuantity,
            feed_type AS feedType
             */
            Response<List<Map<String , Object>>> feedReportMapRes = feedReportReadService.findSumForWeb(map);
            if(!feedReportMapRes.isSuccess()){
                log.error("failed to find sum info , case = {}",feedReportMapRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),feedReportMapRes.getError());
            }
            breedDocumentReportFormDto.setFeedReportInfo(feedReportMapRes.getResult());

            //采购中心数据获取
            //todo 1、原料购置
            Response<Double> totalOfMaterialRes = materialPurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfMaterialRes.isSuccess()){
                log.error("failed to sum total price material , case = {}",totalOfMaterialRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfMaterialRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfMaterialPurchase(totalOfMaterialRes.getResult() == null ? 0.00d : totalOfMaterialRes.getResult());

            /*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> materialInfoRes = materialPurchaseRecordReadService.findMaterialForWeb(map);
            if(!materialInfoRes.isSuccess()){
                log.error("failed to find material info , case = {}",materialInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),materialInfoRes.getError());
            }
            breedDocumentReportFormDto.setMaterialPurchaseReportInfo(materialInfoRes.getResult());

            //todo 2、药物购置
            Response<Double> totalOfDrugRes = drugPurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfDrugRes.isSuccess()){
                log.error("failed to sum total price drug , case = {}",totalOfDrugRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfDrugRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfDrugPurchase(totalOfDrugRes.getResult() == null ? 0.00d : totalOfDrugRes.getResult());
/*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> drugPurchaseInfoRes = drugPurchaseRecordReadService.findDrugPurchaseForWeb(map);
            if(!drugPurchaseInfoRes.isSuccess()){
                log.error("failed to find drug purchase info , case = {}",drugPurchaseInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),drugPurchaseInfoRes.getError());
            }
            breedDocumentReportFormDto.setDrugPurchaseReportInfo(drugPurchaseInfoRes.getResult());

            //todo 3、疫苗购置
            Response<Double> totalOfVaccineRes = vaccinePurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfVaccineRes.isSuccess()){
                log.error("failed to total price for web , case = {}",totalOfVaccineRes);
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfVaccineRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfVaccinePurchase(totalOfVaccineRes.getResult() == null ? 0.00d : totalOfVaccineRes.getResult());
/*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> vaccinePurchaseInfoRes = vaccinePurchaseRecordReadService.findVaccinePurchaseInfoWeb(map);
            if(!vaccinePurchaseInfoRes.isSuccess()){
                log.error("failed to find vaccine purchase , case = {}",vaccinePurchaseInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),vaccinePurchaseInfoRes.getError());
            }
            breedDocumentReportFormDto.setVaccinePurchaseReportInfo(vaccinePurchaseInfoRes.getResult());

            //todo 4、引种记录
            Response<Double> totalOfSeedRes = seedPurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfSeedRes.isSuccess()){
                log.error("failed to sum total price , case = {}",totalOfSeedRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfSeedRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfSeedPurchase(totalOfSeedRes.getResult() == null ? 0.00d : totalOfSeedRes.getResult());
            /*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> seedPurchaseInfoRes = seedPurchaseRecordReadService.findSeedPurchaseInfoWeb(map);
            if(!seedPurchaseInfoRes.isSuccess()){
                log.error("failed to find seed purchase info , case ={}",seedPurchaseInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),seedPurchaseInfoRes.getError());
            }
            breedDocumentReportFormDto.setSeedPurchaseReportInfo(seedPurchaseInfoRes.getResult());

            //todo 5、其他购置
            Response<Double> totalOfOtherRes = otherPurchaseRecordReadService.sumTotalPriceForWeb(map);
            if(!totalOfOtherRes.isSuccess()){
                log.error("failed to sum price , case = {}",totalOfOtherRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),totalOfOtherRes.getError());
            }
            breedDocumentReportFormDto.setTotalOfOtherPurchase(totalOfOtherRes.getResult() == null ? 0.00d : totalOfOtherRes.getResult());

            /*
            SUM (total_price) AS sumTotalPrice,
            AVG (price) AS avgPrice,
            SUM (quantity) AS quantity,
            product_name AS productName
             */
            Response<List<Map<String , Object>>> otherPurchaseInfoRes = otherPurchaseRecordReadService.findOtherPurchaseInfoWeb(map);
            if(!otherPurchaseInfoRes.isSuccess()){
                log.error("failed to find other purchase info web , case = {}",otherPurchaseInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),otherPurchaseInfoRes.getError());
            }
            breedDocumentReportFormDto.setOtherPurchaseReportInfo(otherPurchaseInfoRes.getResult());

            //防疫中心数据获取
            //todo 1、免疫记录

            Response<List<Long>> immunizationIdsRes = immunizationRecordReadService.findIdsForWeb(map);
            if(!immunizationIdsRes.isSuccess()){
                log.error("failed to get immunization ids ,case = {}",immunizationIdsRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),immunizationIdsRes.getError());
            }
            if(immunizationIdsRes.getResult() != null && !immunizationIdsRes.getResult().isEmpty()){
                map.put("vaccineIds",immunizationIdsRes.getResult());
                Response<Integer> countImmunizationRes = immunizationSubRecordReadService.countImmunizationForWeb(map);
                if(!countImmunizationRes.isSuccess()){
                    log.error("failed to count immunization times , case = {}",countImmunizationRes.getError());
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countImmunizationRes.getError());
                }
                breedDocumentReportFormDto.setCountImmunizationRecord(countImmunizationRes.getResult() == null ? 0:countImmunizationRes.getResult());

                /*
                          SUM (quantity) AS quantity,
                          SUM (drug_quantity) AS drugQuantity,
                          vaccine_code AS vaccineCode
                 */
                Response<List<Map<String , Object>>> immunizationInfoRes = immunizationSubRecordReadService.findImmunizationInfoForWeb(map);
                if(!immunizationInfoRes.isSuccess()){
                    log.error("failed to find immunization info , case = {}",immunizationInfoRes.getError());
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),immunizationInfoRes.getError());
                }
                breedDocumentReportFormDto.setImmunizationRecordInfo(immunizationInfoRes.getResult());
            }else {
                breedDocumentReportFormDto.setCountImmunizationRecord(0);
                breedDocumentReportFormDto.setImmunizationRecordInfo(new ArrayList<>());
            }

            //todo 2、消毒记录
            Response<Integer> countDisinfectRes = disinfectReportReadService.countDisinfectForWeb(map);
            if(!countDisinfectRes.isSuccess()){
                log.error("failed to count times , case = {}",countDisinfectRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countDisinfectRes.getError());
            }
            breedDocumentReportFormDto.setCountDisinfect(countDisinfectRes.getResult());

            /*
             SUM (drug_used_quantity) AS drugUsedQuantity,
             disinfectMethod AS disinfectMethod,
             */
            Response<List<Map<String , Object>>> disinfectReportInfoRes = disinfectReportReadService.findDisinfectInfoForWeb(map);
            if(!disinfectReportInfoRes.isSuccess()){
                log.error("failed to find disinfect info , case = {}",disinfectReportInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),disinfectReportInfoRes.getError());
            }
            breedDocumentReportFormDto.setDisinfectReportInfo(disinfectReportInfoRes.getResult());

            //todo 3、诊疗记录
            Response<Integer> countDiagnosisRes = diagnosisReportReadService.countDiagnosisTimesForWeb(map);
            if(!countDiagnosisRes.isSuccess()){
                log.error("failed to count times , case = {}",countDiagnosisRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countDiagnosisRes.getError());
            }
            breedDocumentReportFormDto.setCountDiagnosis(countDiagnosisRes.getResult());

            /*
             SUM (cases) AS cases,
             illness_reason AS illnessReason
             */
            Response<List<Map<String , Object>>> diagnosisInfoRes = diagnosisReportReadService.findDiagnosisInfoForWeb(map);
            if(!diagnosisInfoRes.isSuccess()){
                log.error("failed to find diagnosis info , case = {}",diagnosisInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),diagnosisInfoRes.getError());
            }
            breedDocumentReportFormDto.setDiagnosisReportInfo(diagnosisInfoRes.getResult());

            //todo 4、检验检测
            Response<Integer> countImmunizationDetectionRes = immunizationDetectionReadService.countImmunizationDetectionForWeb(map);
            if(!countImmunizationDetectionRes.isSuccess()){
                log.error("failed to count times , case = {}",countImmunizationDetectionRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),countImmunizationDetectionRes.getError());
            }
            breedDocumentReportFormDto.setCountImmunizationDetection(countImmunizationDetectionRes.getResult());

            /*
             SUM (quantity) AS quantity,
             sample_type AS sampleType
             */
            Response<List<Map<String , Object>>> immunizationDetectionInfoRes = immunizationDetectionReadService.findImmunizationDetectionInfoForWeb(map);
            if(!immunizationDetectionInfoRes.isSuccess()){
                log.error("failed to find immunization detection info , case = {}",immunizationDetectionInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),immunizationDetectionInfoRes.getError());
            }
            breedDocumentReportFormDto.setImmunizationDetectionReportInfo(immunizationDetectionInfoRes.getResult());

            //todo 5、无害化处理
            Response<Integer> sumQuantityHarmlessRes = quarantineCenterHarmlessReadService.sumQuantityHarmlessForWeb(map);
            if(!sumQuantityHarmlessRes.isSuccess()){
                log.error("failed to sum quantity harmless , case = {}",sumQuantityHarmlessRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),sumQuantityHarmlessRes.getError());
            }
            breedDocumentReportFormDto.setSumQuarantineHarmless(sumQuantityHarmlessRes.getResult());

            /*
             SUM (quantity) AS quantity,
             treatment AS treatment
             */
            Response<List<Map<String , Object>>> quarantineHarmlessInfoRes = quarantineCenterHarmlessReadService.findQuarantineHarmlessInfoForWeb(map);
            if(!quarantineHarmlessInfoRes.isSuccess()){
                log.error("failed to find quarantine harmless , case = {}",quarantineHarmlessInfoRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),quarantineHarmlessInfoRes.getError());
            }
            breedDocumentReportFormDto.setQuarantineHarmlessInfo(quarantineHarmlessInfoRes.getResult());


            //治污中心数据获取
            Response<Map<String , Object>> sumPollutionRes = pollutionControlReadService.sumPollutionForWeb(map);
            if(!sumPollutionRes.isSuccess()){
                log.error("failed to sum pollution , case = {}",sumPollutionRes.getError());
                throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),sumPollutionRes.getError());
            }
            Map<String , Object> sumPollutionMap = sumPollutionRes.getResult();
            if(sumPollutionMap != null && !sumPollutionMap.isEmpty()){
                breedDocumentReportFormDto.setSumOfDry((Double) sumPollutionRes.getResult().getOrDefault("dryUsedQuantity",0.00d));
                breedDocumentReportFormDto.setSumOfLiquid((Double) sumPollutionRes.getResult().getOrDefault("liquidUsedQuantity",0.00d));
            }else {
                breedDocumentReportFormDto.setSumOfDry(0.00d);
                breedDocumentReportFormDto.setSumOfLiquid(0.00d);
            }



            breedDocumentReportFormDtos.add(breedDocumentReportFormDto);
        }

        ExportOrImportUtils.dataExportDownloadForDocument(httpServletResponse,buildTitlesOne(),buildTitlesTwo(),buildTitlesThree(),"养殖档案报表", getData(breedDocumentReportFormDtos));
    }

    public List<String> buildTitlesOne(){
        List<String> titles = new ArrayList<>();

        titles.add("养殖场");
        titles.add("养殖品种");
        titles.add("生产中心");
        titles.add("生产中心");
        titles.add("生产中心");
        titles.add("生产中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("采购中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("防疫中心");
        titles.add("治污中心");
        titles.add("治污中心");
        titles.add("备注");

        return titles;
    }

    public List<String> buildTitlesTwo(){
        List<String> titles = new ArrayList<>();

        titles.add("养殖场");
        titles.add("养殖品种");
        titles.add("生产记录");
        titles.add("生产记录");
        titles.add("饲料记录");
        titles.add("饲料记录");
        titles.add("原料购置");
        titles.add("原料购置");
        titles.add("药物购置");
        titles.add("药物购置");
        titles.add("疫苗购置");
        titles.add("疫苗购置");
        titles.add("引种记录");
        titles.add("引种记录");
        titles.add("其他购置");
        titles.add("其他购置");
        titles.add("免疫记录");
        titles.add("免疫记录");
        titles.add("消毒记录");
        titles.add("消毒记录");
        titles.add("诊疗记录");
        titles.add("诊疗记录");
        titles.add("检验检测");
        titles.add("检验检测");
        titles.add("无害化");
        titles.add("无害化");
        titles.add("治污中心");
        titles.add("治污中心");
        titles.add("备注");

        return titles;
    }

    public List<String> buildTitlesThree(){
        List<String> titles = new ArrayList<>();

        titles.add("养殖场");
        titles.add("养殖品种");
        titles.add("变动存栏");
        titles.add("详细");
        titles.add("记录次数");
        titles.add("详细");
        titles.add("总消费（元）");
        titles.add("明细");
        titles.add("总消费（元）");
        titles.add("明细");
        titles.add("总消费（元）");
        titles.add("明细");
        titles.add("总消费（元）");
        titles.add("明细");
        titles.add("总消费（元）");
        titles.add("明细");
        titles.add("免疫次数");
        titles.add("详细");
        titles.add("记录次数");
        titles.add("详细");
        titles.add("记录次数");
        titles.add("详细");
        titles.add("记录次数");
        titles.add("详细");
        titles.add("记录次数");
        titles.add("详细");
        titles.add("干粪利用量(kg)");
        titles.add("沼液利用量(吨)");
        titles.add("备注");

        return titles;

    }

    public List<LinkedHashMap<String , Object>> getData(List<BreedDocumentReportFormDto> result){

        List<LinkedHashMap<String , Object>> data = new ArrayList<>();

        for(BreedDocumentReportFormDto breedDocumentReportFormDto : result){
            LinkedHashMap<String , Object> hashMap = new LinkedHashMap<>();

            hashMap.put("breedFactoryName",breedDocumentReportFormDto.getBreedFactoryName());
            Integer breedType = breedDocumentReportFormDto.getBreedType();
            String breedTypeString = "其他";
            switch (breedType){
                case 1:
                    breedTypeString = "猪";
                    break;
                case 2:
                    breedTypeString = "牛";
                    break;
                case 3:
                    breedTypeString = "羊";
                    break;
                case 4:
                    breedTypeString = "家禽";
                    break;
                case 5:
                    breedTypeString = "其他";
                    break;
                default:
                    break;
            }
            hashMap.put("breedType",breedTypeString);
            hashMap.put("sumProduction",breedDocumentReportFormDto.getSumProduction());

            Map<String , Object> productionInfoO = breedDocumentReportFormDto.getProductionInfo();
            Integer sumBirthQuantity = 0;

            Integer sumChangeQuantity = 0;

            Integer sumDeathQuantity = 0;

            Integer sumInQuantity = 0;

            Integer sumOutQuantity = 0;

            if (productionInfoO != null) {
                sumBirthQuantity = ((BigDecimal) productionInfoO.getOrDefault("sumBirthQuantity",0)).intValue();

                sumChangeQuantity = ((BigDecimal) productionInfoO.getOrDefault("sumChangeQuantity",0)).intValue();

                sumDeathQuantity = ((BigDecimal) productionInfoO.getOrDefault("sumDeathQuantity",0)).intValue();

                sumInQuantity = ((BigDecimal) productionInfoO.getOrDefault("sumInQuantity",0)).intValue();

                sumOutQuantity = ((BigDecimal) productionInfoO.getOrDefault("sumOutQuantity",0)).intValue();
            }
            String productionInfo = "变动存栏：" + sumChangeQuantity + "\n" +
                                    "出生数：" + sumBirthQuantity + "\n" +
                                    "调入数：" + sumInQuantity + "\n" +
                                    "死淘数：" + sumDeathQuantity + "\n" +
                                    "调出数：" + sumOutQuantity;
            hashMap.put("productionInfo",productionInfo);
            hashMap.put("countFeedReport",breedDocumentReportFormDto.getCountFeedReport());
            List<Map<String , Object>> feedReportInfo = breedDocumentReportFormDto.getFeedReportInfo();
            StringBuilder feedReportInfoStr = new StringBuilder();
            for (int i = 0; i < feedReportInfo.size(); i++) {
                Map<String, Object> map = feedReportInfo.get(i);
                Integer feedType = (Integer) map.getOrDefault("feedType", 0);
                String feedTypeName = "其他";
                switch (feedType) {
                    case 1:
                        feedTypeName = "猪饲料";
                        break;
                    case 2:
                        feedTypeName = "羊饲料";
                        break;
                    case 3:
                        feedTypeName = "鸡饲料";
                        break;
                    case 4:
                        feedTypeName = "鸭饲料";
                        break;
                    default:
                        break;
                }
                feedReportInfoStr.append(i + 1)
                        .append("、类型：")
                        .append(feedTypeName)
                        .append(",用量：")
                        .append(map.getOrDefault("sumUsedQuantity", 0))
                        .append(";");
            }
            hashMap.put("feedReportInfo", feedReportInfoStr.toString());
            hashMap.put("totalOfMaterialPurchase",breedDocumentReportFormDto.getTotalOfMaterialPurchase());
            List<Map<String , Object>> materialPurchaseReportInfo = breedDocumentReportFormDto.getMaterialPurchaseReportInfo();
            StringBuilder materialPurchaseReportInfoStr = new StringBuilder();
            for (int i = 0; i < materialPurchaseReportInfo.size(); i++) {
                Map<String, Object> map = materialPurchaseReportInfo.get(i);
                Integer productName = (Integer) map.getOrDefault("productName",5);
                Double sumTotalPrice = (Double) map.getOrDefault("sumTotalPrice",0);
                Double avgPrice = (Double) map.getOrDefault("avgPrice",0);
                Double quantity = (Double) map.getOrDefault("quantity",0);

                //todo productName 判断转化
                String productNameStr = "其它";
                switch (productName) {
                    case 1:
                        productNameStr = "玉米";
                        break;
                    case 2:
                        productNameStr = "豆粕";
                        break;
                    case 3:
                        productNameStr = "麸皮";
                        break;
                    case 4:
                        productNameStr = "鱼粉";
                        break;
                    case 5:
                        productNameStr = "其它";
                        break;
                    default:
                        break;
                }
                materialPurchaseReportInfoStr.append(i + 1)
                        .append("、类型：").append(productNameStr)
                        .append(",数量：").append(quantity)
                        .append(",平均单价：").append(avgPrice)
                        .append(",总价：").append(sumTotalPrice)
                        .append(";");
            }

            hashMap.put("materialPurchaseReportInfo",materialPurchaseReportInfoStr.toString());

            hashMap.put("totalOfDrugPurchase",breedDocumentReportFormDto.getDrugPurchaseReportInfo());
            List<Map<String , Object>> drugPurchaseReportInfo = breedDocumentReportFormDto.getDrugPurchaseReportInfo();
            StringBuilder drugPurchaseReportInfoStr = new StringBuilder();

            for (int i = 0; i < drugPurchaseReportInfo.size(); i++) {
                Map<String, Object> map = drugPurchaseReportInfo.get(i);
                String productName = (String) map.getOrDefault("productName",5);
                Double sumTotalPrice = (Double) map.getOrDefault("sumTotalPrice",0);
                Double avgPrice = (Double) map.getOrDefault("avgPrice",0);
                Double quantity = ((BigDecimal) map.getOrDefault("quantity",0)).doubleValue();

                drugPurchaseReportInfoStr.append(i + 1)
                        .append("、类型：").append(productName)
                        .append(",数量：").append(quantity)
                        .append(",平均单价：").append(avgPrice)
                        .append(",总价：").append(sumTotalPrice)
                        .append(";");
            }
            hashMap.put("drugPurchaseReportInfoStr",drugPurchaseReportInfoStr.toString());

            hashMap.put("totalOfVaccinePurchase",breedDocumentReportFormDto.getTotalOfVaccinePurchase());
            List<Map<String , Object>> vaccinePurchaseReportInfo = breedDocumentReportFormDto.getVaccinePurchaseReportInfo();
            StringBuilder vaccinePurchaseReportInfoStr = new StringBuilder();
            for (int i = 0; i < vaccinePurchaseReportInfo.size(); i++) {
                Map<String, Object> map = vaccinePurchaseReportInfo.get(i);
                Integer productName = (Integer) map.getOrDefault("productName",5);
                Double sumTotalPrice = (Double) map.getOrDefault("sumTotalPrice",0);
                Double avgPrice = (Double) map.getOrDefault("avgPrice",0);
                Double quantity = ((BigDecimal) map.getOrDefault("quantity",0)).doubleValue();
                Map<String , Object> canShu = Maps.newHashMap();
                canShu.put("code",productName);
                canShu.put("type",2);
                canShu.put("deleteFlag",DocumentsDeleteFlag.NORMAL.value());
                Response<DrugOrVaccine> drugOrVaccineResponse = drugOrVaccineReadService.findByCode(canShu);
                if(!drugOrVaccineResponse.isSuccess()){
                    log.error("failed to find , case = {}",drugOrVaccineResponse.getError());
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),drugOrVaccineResponse.getError());
                }
                DrugOrVaccine drugOrVaccine = drugOrVaccineResponse.getResult();
                String name = "";
                if(drugOrVaccine != null){
                    name = drugOrVaccine.getName();
                }
                vaccinePurchaseReportInfoStr.append(i + 1)
                        .append("、类型：").append(name)
                        .append(",数量：").append(quantity)
                        .append(",平均单价：").append(avgPrice)
                        .append(",总价：").append(sumTotalPrice)
                        .append(";");
            }
            hashMap.put("vaccinePurchaseReportInfo",vaccinePurchaseReportInfoStr.toString());

            hashMap.put("totalOfSeedPurchase",breedDocumentReportFormDto.getTotalOfSeedPurchase());

            List<Map<String , Object>> seedPurchaseReportInfo = breedDocumentReportFormDto.getSeedPurchaseReportInfo();
            StringBuilder seedPurchaseReportInfoStr = new StringBuilder();
            for (int i = 0; i < seedPurchaseReportInfo.size(); i++) {
                Map<String, Object> map = seedPurchaseReportInfo.get(i);
                String productName = (String) map.getOrDefault("productName","");
                Double sumTotalPrice = (Double) map.getOrDefault("sumTotalPrice",0);
                Double avgPrice = (Double) map.getOrDefault("avgPrice",0);
                Double quantity = ((BigDecimal) map.getOrDefault("quantity",0)).doubleValue();
                seedPurchaseReportInfoStr.append(i + 1)
                        .append("、类型：").append(productName)
                        .append(",数量：").append(quantity)
                        .append(",平均单价：").append(avgPrice)
                        .append(",总价：").append(sumTotalPrice)
                        .append(";");
            }

            hashMap.put("seedPurchaseReportInfo",seedPurchaseReportInfoStr);

            hashMap.put("totalOfOtherPurchase",breedDocumentReportFormDto.getTotalOfOtherPurchase());
            List<Map<String , Object>> otherPurchaseReportInfo = breedDocumentReportFormDto.getOtherPurchaseReportInfo();
            StringBuilder otherPurchaseReportInfoStr = new StringBuilder();
            for (int i = 0; i < otherPurchaseReportInfo.size(); i++) {
                Map<String, Object> map = otherPurchaseReportInfo.get(i);
                String productName = (String) map.getOrDefault("productName","");
                Double sumTotalPrice = (Double) map.getOrDefault("sumTotalPrice",0);
                Double avgPrice = (Double) map.getOrDefault("avgPrice",0);
                Double quantity = ((BigDecimal) map.getOrDefault("quantity",0)).doubleValue();
                otherPurchaseReportInfoStr.append(i + 1)
                        .append("、类型：").append(productName)
                        .append(",数量：").append(quantity)
                        .append(",平均单价：").append(avgPrice)
                        .append(",总价：").append(sumTotalPrice)
                        .append(";");
            }
            hashMap.put("otherPurchaseReportInfo",otherPurchaseReportInfoStr.toString());
            hashMap.put("countImmunizationRecord",breedDocumentReportFormDto.getCountImmunizationRecord());
            List<Map<String , Object>> immunizationRecordInfo = breedDocumentReportFormDto.getImmunizationRecordInfo();
            StringBuilder immunizationRecordInfoStr = new StringBuilder();
            for (int i = 0; i < immunizationRecordInfo.size(); i++) {
                Map<String, Object> map = immunizationRecordInfo.get(i);
                Integer vaccineCode = (Integer) map.getOrDefault("vaccineCode",0);
                Double drugQuantity = (Double) map.getOrDefault("drugQuantity",0);
                Double quantity = ((BigDecimal) map.getOrDefault("quantity",0)).doubleValue();
                Map<String , Object> canShu = Maps.newHashMap();
                canShu.put("code",vaccineCode);
                canShu.put("type",2);
                canShu.put("deleteFlag",DocumentsDeleteFlag.NORMAL.value());
                Response<DrugOrVaccine> drugOrVaccineResponse = drugOrVaccineReadService.findByCode(canShu);
                if(!drugOrVaccineResponse.isSuccess()){
                    log.error("failed to find , case = {}",drugOrVaccineResponse.getError());
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(),drugOrVaccineResponse.getError());
                }
                DrugOrVaccine drugOrVaccine = drugOrVaccineResponse.getResult();
                String name = "";
                if(drugOrVaccine != null){
                    name = drugOrVaccine.getName();
                }
                immunizationRecordInfoStr.append(i + 1)
                        .append("、疫苗类型：").append(name)
                        .append(",免疫数量：").append(quantity)
                        .append(",用药量：").append(drugQuantity)
                        .append(";");
            }
            hashMap.put("immunizationRecordInfo",immunizationRecordInfoStr.toString());

            hashMap.put("countDisinfect",breedDocumentReportFormDto.getCountDisinfect());
            List<Map<String , Object>> disinfectReportInfo = breedDocumentReportFormDto.getDisinfectReportInfo();
            StringBuilder disinfectReportInfoStr = new StringBuilder();
            for (int i = 0; i < disinfectReportInfo.size(); i++) {
                Map<String, Object> map = disinfectReportInfo.get(i);
                Integer disinfectMethod = (Integer) map.getOrDefault("disinfectMethod",0);
                Double drugUsedQuantity = (Double) map.getOrDefault("drugUsedQuantity",0);
                String disinfectMethodStr = "其他";
                if (disinfectMethod == 1) {
                    disinfectMethodStr = "喷雾";
                } else if (disinfectMethod == 2) {
                    disinfectMethodStr = "其他";
                }
                disinfectReportInfoStr.append(i + 1)
                        .append("、消毒方法：").append(disinfectMethodStr)
                        .append(",用药量：").append(drugUsedQuantity)
                        .append(";");
            }

            hashMap.put("disinfectReportInfo",disinfectReportInfoStr.toString());

            hashMap.put("countDiagnosis",breedDocumentReportFormDto.getCountDiagnosis());

            List<Map<String , Object>> diagnosisReportInfo = breedDocumentReportFormDto.getDiagnosisReportInfo();
            StringBuilder diagnosisReportInfoStr = new StringBuilder();
            for (int i = 0; i < diagnosisReportInfo.size(); i++) {
                Map<String, Object> map = diagnosisReportInfo.get(i);
                String illnessReason = (String) map.getOrDefault("illnessReason","");
                Double cases = ((BigDecimal) map.getOrDefault("cases",0)).doubleValue();
                diagnosisReportInfoStr.append(i + 1)
                        .append("、消毒方法：").append(illnessReason)
                        .append(",发病数：").append(cases)
                        .append(";");
            }

            hashMap.put("diagnosisReportInfo",diagnosisReportInfoStr.toString());

            hashMap.put("countImmunizationDetection",breedDocumentReportFormDto.getCountImmunizationDetection());
            List<Map<String , Object>> immunizationDetectionReportInfo = breedDocumentReportFormDto.getImmunizationDetectionReportInfo();
            StringBuilder immunizationDetectionReportInfoStr = new StringBuilder();
            for (int i = 0; i < immunizationDetectionReportInfo.size(); i++) {
                Map<String, Object> map = immunizationDetectionReportInfo.get(i);
                Integer sampleType = (Integer) map.getOrDefault("sampleType",0);
                Double quantity = ((BigDecimal) map.getOrDefault("quantity",0)).doubleValue();

                String sampleTypeName = "其他";
                switch (sampleType) {
                    case 1:
                        sampleTypeName = "血样";
                        break;
                    case 2:
                        sampleTypeName = "尿样";
                        break;
                    case 3:
                        sampleTypeName = "奶样";
                        break;
                    case 4:
                        sampleTypeName = "蛋样";
                        break;
                    case 5:
                        sampleTypeName = "兽药";
                        break;
                    case 6:
                        sampleTypeName = "饲料";
                        break;
                    default:
                        break;
                }
                immunizationDetectionReportInfoStr.append(i + 1)
                        .append("、样本类型：").append(sampleTypeName)
                        .append(",检测数量：").append(quantity)
                        .append(";");
            }
            hashMap.put("immunizationDetectionReportInfo",immunizationDetectionReportInfoStr.toString());

            hashMap.put("sumQuarantineHarmless",breedDocumentReportFormDto.getSumQuarantineHarmless());

            List<Map<String , Object>> quarantineHarmlessInfo = breedDocumentReportFormDto.getQuarantineHarmlessInfo();
            StringBuilder quarantineHarmlessInfoStr = new StringBuilder();
            for (int i = 0; i < diagnosisReportInfo.size(); i++) {
                Map<String, Object> map = diagnosisReportInfo.get(i);
                Integer treatment = (Integer) map.getOrDefault("treatment",0);
                Integer quantity = (Integer) map.getOrDefault("quantity",0);
                String treatmentName = "其它";
                switch (treatment) {
                    case 1:
                        treatmentName = "集中处理";
                        break;
                    case 2:
                        treatmentName = "焚烧";
                        break;
                    case 3:
                        treatmentName = "化制";
                        break;
                    case 4:
                        treatmentName = "深埋";
                        break;
                    case 5:
                        treatmentName = "发酵";
                        break;
                    case 6:
                        treatmentName = "其它";
                        break;
                    default:
                        break;
                }

                quarantineHarmlessInfoStr.append(i + 1)
                        .append("、处理方式：").append(treatmentName)
                        .append(",数量：").append(quantity)
                        .append(";");
            }
            hashMap.put("quarantineHarmlessInfo",quarantineHarmlessInfoStr.toString());

            hashMap.put("sumOfDry",breedDocumentReportFormDto.getSumOfDry());
            hashMap.put("sumOfLiquid",breedDocumentReportFormDto.getSumOfLiquid());
            data.add(hashMap);
        }

        return data;
    }

    @GetMapping("/djt/report/breedDocumentModel")
    public String getExcelModel(){
        return "/djt/report/breedDocumentModel";
    }


    public Map<String, Object> getarea(HttpServletResponse response, HttpServletRequest request) {
        List<String> list = new ArrayList<>();
        list.add("province");
        list.add("city");
        list.add("region");
        list.add("street");
        list.add("village");
        Cookie[] cookies = null;
        cookies = request.getCookies();
        String name = "";
        Map<String, Object> loginUserMap = Maps.newHashMap();
        for (Cookie cookie : cookies) {

            if (cookie.getName().equals("djtid")) {
                String id = cookie.getValue();
                int Id = Integer.parseInt(id);
                Response<User> userResponse = userReadService.findById(Long.valueOf(id));
                name = userResponse.getResult().getName();
                loginUserMap.put("username", name);
                UserProfile userProfile = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                loginUserMap.put("userProfile", userProfile);
                switch (userResponse.getResult().getAreaLevel()) {
                    case 1:
                        String Province = userProfile.getProvince();
                        Map<String, Object> map6 = Maps.newHashMap();
                        map6.put("province", Province);
                        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map6).getResult();
                        //获取所有省下城市

                        Map<String, Object> map1 = Maps.newHashMap();
                        map1.put("area1", list.get(1));
                        map1.put("area2", list.get(0));
                        map1.put("area3", Province);
                        List<String> citys = breedFactoryReadService.serachAllregion1(map1);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList = new ArrayList<>();
                        for (String city : citys) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map<String, Object> map2 = Maps.newHashMap();
                            map2.put("area1", list.get(2));
                            map2.put("area2", list.get(1));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList.add(cityAreaDto);

                        }
                        loginUserMap.put("cityAreaDtoList", cityAreaDtoList);
                        loginUserMap.put("breedFactorys", breedFactoryList);
                        //switch break;
                        break;
                    case 2:
                        String city1 = userProfile.getCity();
                        Map<String, Object> map7 = Maps.newHashMap();
                        map7.put("city", city1);
                        List<BreedFactory> breedFactoryList1 = (List<BreedFactory>) breedFactoryReadService.findByArea(map7).getResult();
                        //获取所有省下城市

                        Map<String, Object> map21 = Maps.newHashMap();
                        map21.put("area1", list.get(2));
                        map21.put("area2", list.get(1));
                        map21.put("area3", city1);
                        List<String> citys2 = breedFactoryReadService.serachAllregion1(map21);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList1 = new ArrayList<>();
                        for (String city : citys2) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map<String, Object> map2 = Maps.newHashMap();
                            map2.put("area1", list.get(3));
                            map2.put("area2", list.get(2));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList1.add(cityAreaDto);

                        }
                        loginUserMap.put("cityAreaDtoList", cityAreaDtoList1);
                        loginUserMap.put("breedFactorys", breedFactoryList1);
                        //switch break;
                        break;
                    case 3://区
                        String region = userProfile.getRegion();
                        Map<String, Object> map36 = Maps.newHashMap();
                        map36.put("region", region);
                        List<BreedFactory> breedFactoryList3 = (List<BreedFactory>) breedFactoryReadService.findByArea(map36).getResult();
                        //获取所有区下城市镇

                        Map<String, Object> map31 = Maps.newHashMap();
                        map31.put("area1", list.get(3));
                        map31.put("area2", list.get(2));
                        map31.put("area3", region);
                        List<String> citys3 = breedFactoryReadService.serachAllregion1(map31);
                        //获取对应镇 对应村
                        List<CityAreaDto> cityAreaDtoList3 = new ArrayList<>();
                        for (String city : citys3) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map<String, Object> map2 = Maps.newHashMap();
                            map2.put("area1", list.get(4));
                            map2.put("area2", list.get(3));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList3.add(cityAreaDto);

                        }
                        loginUserMap.put("cityAreaDtoList", cityAreaDtoList3);
                        loginUserMap.put("breedFactorys", breedFactoryList3);
                        //switch break;
                        break;
                    case 4://镇
                        String street = userProfile.getStreet();
                        Map<String, Object> map46 = Maps.newHashMap();
                        map46.put("street", street);
                        List<BreedFactory> breedFactoryList4 = (List<BreedFactory>) breedFactoryReadService.findByArea(map46).getResult();
                        //获取所有镇下所有村

                        Map<String, Object> map41 = Maps.newHashMap();
                        map41.put("area1", list.get(4));
                        map41.put("area2", list.get(3));
                        map41.put("area3", street);
                        List<String> citys4 = breedFactoryReadService.serachAllregion1(map41);//所有村

                        List<CityAreaDto> cityAreaDtoList4 = new ArrayList<>();

                        CityAreaDto cityAreaDto = new CityAreaDto();

                        cityAreaDto.setCity(street);
                        cityAreaDto.setRegions(citys4);
                        cityAreaDtoList4.add(cityAreaDto);

                        loginUserMap.put("cityAreaDtoList", cityAreaDtoList4);
                        loginUserMap.put("breedFactorys", breedFactoryList4);
                        //switch break;
                        break;
                    case 5://村
                        List<GovernmentUserDuty> governmentUserDutyList = governmentUserDutyReadService.findGovernmentUserDutiesByUserId(userResponse.getResult().getId(), null).getResult();
                        List<Long> longlist = new ArrayList<>();
                        for (GovernmentUserDuty governmentUserDuty : governmentUserDutyList) {
                            longlist.add(governmentUserDuty.getFactoryOrPointId());
                        }
                        List<String> villages = new ArrayList<>();
                        List<BreedFactory> breedFactoryList2 = breedFactoryReadService.findBreedFactoryDtoByIds(longlist).getResult();
                        for (BreedFactory breedFactory : breedFactoryList2) {
                            villages.add(breedFactory.getVillage());

                        }

                        List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(villages));


                        List<CityAreaDto> cityAreaDtoList5 = new ArrayList<>();

                        CityAreaDto cityAreaDto1 = new CityAreaDto();
                        cityAreaDto1.setCity(" ");

                        // cityAreaDto1.setCity(village);
                        cityAreaDto1.setRegions(listWithoutDup);

                        cityAreaDtoList5.add(cityAreaDto1);

                        loginUserMap.put("cityAreaDtoList", cityAreaDtoList5);
                        loginUserMap.put("breedFactorys", breedFactoryList2);
                        //switch break;
                        break;
                }

                Response<List<GovernmentUserDuty>> response1 = governmentUserDutyReadService.findGovernmentUserDutiesByUserId(userResponse.getResult().getId(), null);
                if (!response1.isSuccess()) {
                    log.error("failed to find user info ");
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(), response1.getError());
                }
                List<DeclareStation> declareStations = new ArrayList<>();
                List<ButcherFactory> butcherFactories = new ArrayList<>();
                List<Long> declareStationIds = new ArrayList<>();
                List<Long> butcherFactoryIds = new ArrayList<>();
                for (GovernmentUserDuty governmentUserDuty : response1.getResult()) {
                    if (governmentUserDuty.getFactoryOrPointType() == 2) {
                        declareStationIds.add(governmentUserDuty.getFactoryOrPointId());
                    } else if (governmentUserDuty.getFactoryOrPointType() == 1) {
                        butcherFactoryIds.add(governmentUserDuty.getFactoryOrPointId());
                    }
                }
                Response<List<DeclareStation>> response2 = declareStationReadService.findByIds(declareStationIds);
                if (!response2.isSuccess()) {
                    log.error("failed to find ");
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(), response2.getError());
                }
                declareStations = response2.getResult();
                loginUserMap.put("declareStations", declareStations);
                loginUserMap.put("declareStationIds", declareStationIds);
                Response<List<ButcherFactory>> response3 = butcherFactoryReadService.findByIds(butcherFactoryIds);
                if (!response3.isSuccess()) {
                    log.error("failed to find ");
                    throw new OPServerException(ExceptionCode.DATA_NOT_FOUND.value(), response3.getError());
                }
                butcherFactories = response3.getResult();
                loginUserMap.put("butcherFactories", butcherFactories);
                loginUserMap.put("butcherFactoryIds", butcherFactoryIds);

                break;
            }
        }

        return loginUserMap;
    }
}
